
#include "Threadpool.h"
#include "MyThread.h"
#include <unistd.h>
Threadpool::Threadpool(int threadNum, int queSize)
:_threads()
,_threadNum(threadNum)
,_que(queSize)
,_queSize(queSize)
,_isExit(false)
{

}

Threadpool::~Threadpool()
{

}

void Threadpool::start()
{
    for(int i = 0; i < _threadNum; ++i)
    {
        unique_ptr<Thread> threadptr(new MyThread(*this));
        _threads.push_back(std::move(threadptr));
    }
    for(auto & ele : _threads)
    {
        ele->start();
    }
}
void Threadpool::addTask(Task * task)
{
    if(task)
        _que.push(task);
}


void Threadpool::doTask()
{
    while(!_isExit)
    {
        Task *task = _que.pop();
        if(task)
            task->process();
            delete task;

    }
}

void Threadpool::stop()
{
    while(!_que.empty())
    {
        sleep(1);
    }
    if(!_isExit)
    {
        _isExit = true;
        _que.wakeup();
        for(int i = 0; i < _threadNum; ++i)
        {
            _threads[i]->join();
        }

    }

}
